What is js-stringify?
The js-stringify npm package is used to safely serialize JavaScript values to JSON strings. It ensures that the output is a valid JavaScript string literal, which can be useful for embedding data in HTML or JavaScript code.
What are js-stringify's main functionalities?
Basic Stringify
This feature allows you to convert a JavaScript object into a JSON string. The output is a valid JavaScript string literal.
const stringify = require('js-stringify');
const obj = { key: 'value' };
const str = stringify(obj);
console.log(str); // Output: '{"key":"value"}'
Stringify with Special Characters
This feature ensures that special characters within the string are properly escaped, making the output safe for embedding in JavaScript code.
const stringify = require('js-stringify');
const obj = { key: 'value with special characters: \n \t' };
const str = stringify(obj);
console.log(str); // Output: '{"key":"value with special characters: \n \t"}'
Stringify Arrays
This feature allows you to convert arrays into JSON strings, ensuring that all elements are properly serialized.
const stringify = require('js-stringify');
const arr = [1, 'two', { three: 3 }];
const str = stringify(arr);
console.log(str); // Output: '[1,"two",{"three":3}]'
Other packages similar to js-stringify
json-stringify-safe
The json-stringify-safe package provides a safer version of JSON.stringify that can handle circular references without throwing errors. Unlike js-stringify, it focuses on preventing crashes due to circular structures rather than ensuring the output is a valid JavaScript string literal.
fast-json-stringify
The fast-json-stringify package is designed for high performance JSON serialization. It uses JSON schema to generate optimized serialization code. While it is faster than js-stringify, it does not focus on ensuring the output is a valid JavaScript string literal.
safe-stable-stringify
The safe-stable-stringify package provides deterministic and safe JSON.stringify functionality, ensuring consistent output for the same input. It also handles circular references. Unlike js-stringify, it focuses on stability and safety rather than embedding data in JavaScript code.
js-stringify
Stringify an object so it can be safely inlined in JavaScript code
Installation
npm install js-stringify
Usage
var assert = require('assert');
var stringify = require('js-stringify');
assert(stringify('foo') === '"foo"');
assert(stringify('foo\u2028bar\u2029baz') === '"foo\\u2028bar\\u2029baz"');
assert(stringify(new Date('2014-12-19T03:42:00.000Z')) === 'new Date("2014-12-19T03:42:00.000Z")');
assert(stringify({foo: 'bar'}) === '{"foo":"bar"}');
assert(stringify(undefined) === 'undefined');
assert(stringify(null) === 'null');
assert(
stringify({val: "</script><script>alert('bad actor')</script>"}) ===
'{"val":"\\u003C\\u002Fscript\\u003E\\u003Cscript\\u003Ealert(\'bad actor\')\\u003C\\u002Fscript\\u003E"}'
);
License
MIT